import _regeneratorRuntime from "@babel/runtime/regenerator";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";
import _cloneDeep from "lodash/cloneDeep";
var _excluded = ["cardId"],
    _excluded2 = ["i"];

var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _dec10, _dec11, _dec12, _dec13, _dec14, _dec15, _dec16, _class, _class2, _class3;

import React from 'react';
import ReactDOM from 'react-dom';
import { connect } from 'dva';
import RGL from 'react-grid-layout';
import 'react-grid-layout/css/styles.css';
import 'react-resizable/css/styles.css';
import { Button, Card, Icon } from 'antd';
import { Bind, Debounce } from 'lodash-decorators'; // 可能会被其他页面当作组件使用, 所以需要这个注解注入 match

import { withRouter } from 'dva/router';
import intl from "../../../utils/intl";
import { Content, Header } from "../../../components/Page";
import formatterCollections from "../../../utils/intl/formatterCollections";
import notification from "../../../utils/notification";
import { DEBOUNCE_TIME } from "../../../utils/constants";
import { loadCardAsync, setCard } from "../../../customize/cards";
import styles from "./index.less?modules";
import CardsSetting from "./CardsSetting";
var ReactGridLayout = RGL; // 将一样的不会变化的样式 抽取出来 放在最外面

var pageContentStyle = {
  backgroundColor: 'rgb(243, 244, 245)',
  padding: '0 6px 0 6px'
};
var layoutContainerStyle = {
  position: 'relative'
};
var buttonStyle = {
  float: 'right',
  marginRight: '12px'
};
var setLayoutButtonStyle = {
  // border: 'none',
  float: 'right',
  marginRight: '12px'
};
var Workplace = (_dec = connect(function (_ref) {
  var workplace = _ref.workplace,
      loading = _ref.loading,
      _ref$global = _ref.global,
      global = _ref$global === void 0 ? {} : _ref$global;
  return {
    workplace: workplace,
    loadAssignableCardsLoading: loading.effects['workplace/fetchCards'],
    activeTabKey: global.activeTabKey
  };
}), _dec2 = formatterCollections({
  code: ['cpaas.workplace']
}), _dec3 = Bind(), _dec4 = Debounce(DEBOUNCE_TIME), _dec5 = Bind(), _dec6 = Bind(), _dec7 = Bind(), _dec8 = Bind(), _dec9 = Bind(), _dec10 = Bind(), _dec11 = Bind(), _dec12 = Bind(), _dec13 = Bind(), _dec14 = Bind(), _dec15 = Bind(), _dec16 = Bind(), _dec(_class = withRouter(_class = _dec2(_class = (_class2 = (_class3 = /*#__PURE__*/function (_React$Component) {
  _inherits(Workplace, _React$Component);

  var _super = _createSuper(Workplace);

  // 初始化的卡片, {[code: string]: card}; // 存储初始化的卡片
  function Workplace(props) {
    var _this;

    _classCallCheck(this, Workplace);

    _this = _super.call(this, props); // 存储进入设计状态之前的 layout

    _this.initCards = {};
    _this.state = {
      modalVisible: false,
      // 编辑状态是否可见
      loading: true,
      //
      setting: false,
      // 设计状态
      layout: [],
      // 现有的布局数据
      cards: [],
      // 现有的布局 对应的 组件
      currentCards: [] // 当前布局内卡片的原始数据

    };
    _this.originLayout = null;
    _this.originCurrentCards = null;
    _this.mounted = false; // 表示组件是否加载

    var _props$cardsConfig = props.cardsConfig,
        cardsConfig = _props$cardsConfig === void 0 ? [] : _props$cardsConfig;
    cardsConfig.forEach(function (cardConfig) {
      setCard(cardConfig);
    });
    return _this;
  }

  _createClass(Workplace, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var _this2 = this;

      // this.loadCards(this.fetchLayout());
      var dispatch = this.props.dispatch;
      dispatch({
        type: 'workplace/fetchLayoutAndInit'
      }).then(function (res) {
        if (res) {
          _this2.setState({
            currentCards: res
          });

          _this2.loadCards(res.map(function (card) {
            var cardId = card.cardId,
                rest = _objectWithoutProperties(card, _excluded);

            if (card.initFlag === 1) {
              _this2.initCards[String(cardId)] = card;
            }

            return _objectSpread(_objectSpread({}, rest), {}, {
              i: String(cardId)
            });
          }));
        }
      });
      this.mounted = true; // 监听 windowResize

      window.addEventListener('resize', this.handleWindowResize);
      this.handleWindowResize();
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      this.mounted = false; // 移除监听 windowResize

      window.removeEventListener('resize', this.handleWindowResize);
      this.handleWindowResize.cancel();
    } // eslint-disable-next-line no-unused-vars

  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps, prevState, snapshot) {
      if (this.needUpdateWidth) {
        this.needUpdateWidth = false;
        this.handleWindowResize();
      }
    }
    /**
     * 是 初始化卡片
     * @param {string} cardId - 卡片Id
     */

  }, {
    key: "isInitCard",
    value: function isInitCard(cardId) {
      return !!this.initCards[cardId];
    }
    /**
     * window resize 后 重新设置宽度
     */

  }, {
    key: "handleWindowResize",
    value: function handleWindowResize() {
      if (!this.mounted) {
        // 如果组件没有在组件树中, 则不重新设置宽度
        return;
      }

      var _this$props = this.props,
          path = _this$props.match.path,
          activeTabKey = _this$props.activeTabKey;

      if (path !== activeTabKey) {
        // 如果当前 tab 页 不是本页面, 则不更新 width, 但是要设置 标志, 在 DidUpdate 中更新
        this.needUpdateWidth = true;
        return;
      } // eslint-disable-next-line


      var node = ReactDOM.findDOMNode(this); // Flow casts this to Text | Element

      if (node instanceof HTMLElement) {
        this.setState({
          width: node.offsetWidth
        });
      }
    }
  }, {
    key: "renderCard",
    value: function renderCard() {
      var _this3 = this;

      var _this$state = this.state,
          _this$state$setting = _this$state.setting,
          setting = _this$state$setting === void 0 ? false : _this$state$setting,
          _this$state$cards = _this$state.cards,
          cards = _this$state$cards === void 0 ? [] : _this$state$cards;
      return cards.map(function (item) {
        // TODO: GridItem need width
        if (setting === true) {
          return /*#__PURE__*/React.createElement("div", {
            key: item.name
          }, item.component, /*#__PURE__*/React.createElement("div", {
            className: styles.dragCard
          }), !_this3.isInitCard(item.name) && /*#__PURE__*/React.createElement(Icon, {
            type: "close",
            className: styles.closeBtn,
            onClick: function onClick() {
              _this3.handleRemoveCard(item.name);
            }
          }));
        }

        return /*#__PURE__*/React.createElement("div", {
          key: item.name,
          className: styles.boxShadow
        }, item.component);
      });
    }
    /**
     * layout 改变的回调
     */

  }, {
    key: "onLayoutChange",
    value: function onLayoutChange(layout) {
      // 现在错误的 卡片也会占一个位置了
      // if (layout.length === 1 && layout[0].name === 'error') return;
      this.setState({
        layout: layout
      });
    }
    /**
     * 保存布局
     */

  }, {
    key: "saveLayout",
    value: function saveLayout() {
      var _this4 = this;

      var _this$state2 = this.state,
          layout = _this$state2.layout,
          currentCards = _this$state2.currentCards;
      var dispatch = this.props.dispatch;
      this.setState({
        setting: false
      }, function () {
        if (layout) {
          var newLayout = _cloneDeep(layout);

          var saveParams = newLayout.map(function (item) {
            var i = item.i,
                rest = _objectWithoutProperties(item, _excluded2);

            var card = currentCards.find(function (n) {
              return String(n.cardId) === i;
            });
            var cardId = card.cardId,
                code = card.code,
                cardParams = card.cardParams,
                name = card.name;
            return _objectSpread(_objectSpread({}, rest), {}, {
              cardId: cardId,
              code: code,
              name: name,
              cardParams: cardParams
            });
          });
          dispatch({
            type: 'workplace/saveLayout',
            payload: _toConsumableArray(saveParams)
          }).then(function (res) {
            if (res) {
              notification.success();
              _this4.originLayout = layout;
              _this4.originCurrentCards = currentCards;
            } else {
              _this4.loadCards(_this4.originLayout);
            }
          }).catch(function () {
            _this4.loadCards(_this4.originLayout);
          });
        }
      });
    }
    /**
     * 开始设置布局
     */

  }, {
    key: "startSettingLayout",
    value: function startSettingLayout() {
      var _this5 = this;

      var _this$state3 = this.state,
          layout = _this$state3.layout,
          currentCards = _this$state3.currentCards;
      this.setState({
        setting: true
      }, function () {
        _this5.originLayout = layout;
        _this5.originCurrentCards = currentCards;
      });
    }
    /**
     * 取消设置布局状态
     */

  }, {
    key: "cancelSettingLayout",
    value: function cancelSettingLayout() {
      this.loadCards(this.originLayout, true);
      this.setState({
        setting: false,
        currentCards: this.originCurrentCards
      });
    }
    /**
     * 加载单独的卡片组件, 失败返回 失败的Card
     * @param {string} cardCode - 卡片代码
     * @return {React.Component|null}
     */

  }, {
    key: "importCard",
    value: function () {
      var _importCard = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(cardCode) {
        var loadCard;
        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                loadCard = null;
                _context.prev = 1;
                _context.next = 4;
                return loadCardAsync(cardCode);

              case 4:
                loadCard = _context.sent;
                _context.next = 10;
                break;

              case 7:
                _context.prev = 7;
                _context.t0 = _context["catch"](1);
                loadCard = null;

              case 10:
                return _context.abrupt("return", loadCard);

              case 11:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, null, [[1, 7]]);
      }));

      function importCard(_x) {
        return _importCard.apply(this, arguments);
      }

      return importCard;
    }()
    /**
     * 加载所有的卡片组件
     */

  }, {
    key: "importCards",
    value: function () {
      var _importCards = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
        var _this6 = this;

        var _len,
            cardCodes,
            _key,
            _args2 = arguments;

        return _regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                for (_len = _args2.length, cardCodes = new Array(_len), _key = 0; _key < _len; _key++) {
                  cardCodes[_key] = _args2[_key];
                }

                return _context2.abrupt("return", Promise.all(cardCodes.map(function (cardCode) {
                  return _this6.importCard(cardCode);
                })));

              case 2:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2);
      }));

      function importCards() {
        return _importCards.apply(this, arguments);
      }

      return importCards;
    }()
    /**
     * 查找id相同的card
     * @param {string} i
     */

  }, {
    key: "getCard",
    value: function getCard(i, flag) {
      var currentCards = this.state.currentCards;
      return !flag ? currentCards.find(function (n) {
        return String(n.cardId) === i;
      }) : this.originCurrentCards.find(function (n) {
        return String(n.cardId) === i;
      });
    }
    /**
     * 将 卡片 加载成 layout
     */

  }, {
    key: "loadCards",
    value: function loadCards() {
      var _this7 = this;

      var layouts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
      var flag = arguments.length > 1 ? arguments[1] : undefined;
      var layout = layouts;
      var cards = [];
      this.importCards.apply(this, _toConsumableArray(layout.map(function (c) {
        return _this7.getCard(c.i, flag).code;
      }))).then(function (cmps) {
        cards = layout.map(function (card, index) {
          var data = _this7.getCard(card.i);

          var cmp = cmps[index];

          if (cmp) {
            if (cmp.__esModule) {
              var _WorkplaceCard = cmp.default;
              return {
                name: card.i,
                component: /*#__PURE__*/React.createElement(_WorkplaceCard, {
                  cardParams: data.cardParams,
                  name: data.name
                })
              };
            }

            var WorkplaceCard = cmp;
            return {
              name: card.i,
              component: /*#__PURE__*/React.createElement(WorkplaceCard, {
                cardParams: data.cardParams,
                name: data.name
              })
            };
          }

          return {
            name: card.i,
            component: /*#__PURE__*/React.createElement(Card, {
              loading: true
            })
          };
        });
      }).finally(function () {
        _this7.setState({
          loading: false,
          layout: layout,
          cards: cards
        });
      });
    }
    /**
     * 移除指定 id 的卡片
     */

  }, {
    key: "handleRemoveCard",
    value: function handleRemoveCard(id) {
      var _this8 = this;

      var _this$state4 = this.state,
          _this$state4$layout = _this$state4.layout,
          layout = _this$state4$layout === void 0 ? [] : _this$state4$layout,
          _this$state4$currentC = _this$state4.currentCards,
          currentCards = _this$state4$currentC === void 0 ? [] : _this$state4$currentC;
      var layouts = layout.filter(function (l) {
        return l.i !== id;
      });
      var cards = currentCards.filter(function (l) {
        return l.cardId !== id;
      });

      if (layouts.length === layout.length) {// 已经移除了 不要重复移除
        // FIXME: 是否在 CardsSetting 中判断
      }

      this.setState({
        currentCards: cards
      }, function () {
        _this8.loadCards(layouts);
      });
    }
  }, {
    key: "handleAddCard",
    value: function handleAddCard(card) {
      var _this9 = this;

      var _this$state5 = this.state,
          _this$state5$layout = _this$state5.layout,
          layout = _this$state5$layout === void 0 ? [] : _this$state5$layout,
          _this$state5$currentC = _this$state5.currentCards,
          currentCards = _this$state5$currentC === void 0 ? [] : _this$state5$currentC;
      var cardId = card.cardId;

      if (layout.some(function (l) {
        return l.i === String(cardId);
      })) {
        // 已经添加了 不要重复添加
        // FIXME: 是否在 CardsSetting 中判断
        return;
      }

      var layouts = [].concat(_toConsumableArray(layout), [_objectSpread(_objectSpread({}, card), {}, {
        i: String(cardId)
      })]);
      currentCards.push(card);
      this.setState({
        currentCards: currentCards
      }, function () {
        _this9.loadCards(layouts);
      });
    }
    /**
     * 关闭卡片设置页面
     */

  }, {
    key: "hideModal",
    value: function hideModal() {
      this.setState({
        modalVisible: false
      });
    }
    /**
     * 打开卡片设置页面
     * 先打开 卡片设置页面, 同时加载可以分配的卡片
     */

  }, {
    key: "showModal",
    value: function showModal() {
      this.setState({
        modalVisible: true
      });
    }
    /**
     * 加载可以分配的卡片
     */

  }, {
    key: "loadAssignableCards",
    value: function loadAssignableCards() {
      var _this$props2 = this.props,
          dispatch = _this$props2.dispatch,
          roleCards = _this$props2.workplace.roleCards;
      return dispatch({
        type: 'workplace/fetchCards',
        payload: {
          roleCards: roleCards
        }
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props3 = this.props,
          _this$props3$workplac = _this$props3.workplace,
          prevRoleCards = _this$props3$workplac.prevRoleCards,
          _this$props3$workplac2 = _this$props3$workplac.roleCards,
          roleCards = _this$props3$workplac2 === void 0 ? [] : _this$props3$workplac2,
          _this$props3$workplac3 = _this$props3$workplac.catalogType,
          catalogType = _this$props3$workplac3 === void 0 ? [] : _this$props3$workplac3,
          loadAssignableCardsLoading = _this$props3.loadAssignableCardsLoading;
      var _this$state6 = this.state,
          _this$state6$setting = _this$state6.setting,
          setting = _this$state6$setting === void 0 ? false : _this$state6$setting,
          _this$state6$layout = _this$state6.layout,
          layout = _this$state6$layout === void 0 ? [] : _this$state6$layout,
          _this$state6$loading = _this$state6.loading,
          loading = _this$state6$loading === void 0 ? true : _this$state6$loading,
          _this$state6$modalVis = _this$state6.modalVisible,
          modalVisible = _this$state6$modalVis === void 0 ? false : _this$state6$modalVis,
          width = _this$state6.width;
      var allCards = this.renderCard();
      var reactGridLayoutProps = {};

      if (width) {
        reactGridLayoutProps.width = width;
      }

      return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Header, {
        title: intl.get('cpaas.workplace.view.title.myWorkplace').d('我的工作台')
      }, loading !== true && /*#__PURE__*/React.createElement("div", {
        style: {
          flex: '1 auto'
        }
      }, setting === true ? /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Button, {
        type: "primary",
        icon: "save",
        style: buttonStyle,
        onClick: this.saveLayout
      }, intl.get('cpaas.common.button.save').d('保存')), /*#__PURE__*/React.createElement(Button, {
        style: buttonStyle,
        icon: "minus-circle-o",
        onClick: this.cancelSettingLayout
      }, intl.get('cpaas.common.button.cancel').d('取消')), /*#__PURE__*/React.createElement(Button, {
        icon: "setting",
        style: buttonStyle,
        onClick: this.showModal
      }, intl.get('cpaas.workplace.view.title.cardsSetting').d('卡片设置'))) : /*#__PURE__*/React.createElement(Button, {
        icon: "layout",
        style: setLayoutButtonStyle,
        onClick: this.startSettingLayout
      }, intl.get('cpaas.common.button.settingLayout').d('设置布局')))), /*#__PURE__*/React.createElement(Content, {
        noCard: true,
        style: pageContentStyle
      }, loading === true ? /*#__PURE__*/React.createElement(Card, {
        loading: true
      }) : /*#__PURE__*/React.createElement(ReactGridLayout, Object.assign({}, reactGridLayoutProps, {
        style: layoutContainerStyle,
        layout: layout,
        className: styles.gridLayoutContainer,
        isDraggable: setting,
        isResizable: setting,
        cols: 120,
        rowHeight: 1,
        margin: [12, 12],
        onLayoutChange: this.onLayoutChange
      }), allCards), /*#__PURE__*/React.createElement(CardsSetting, {
        loading: loadAssignableCardsLoading,
        loadAssignableCards: this.loadAssignableCards,
        onRemoveCard: this.handleRemoveCard,
        onAddCard: this.handleAddCard,
        onCancel: this.hideModal,
        loadCards: this.loadCards,
        prevRoleCards: prevRoleCards,
        roleCards: roleCards,
        visible: modalVisible,
        layout: layout,
        catalogType: catalogType,
        isInitCard: this.isInitCard,
        getCard: this.getCard
      })));
    }
  }]);

  return Workplace;
}(React.Component), _class3.defaultProps = {
  className: styles.gridLayoutContainer,
  cols: 20,
  rowHeight: 28
}, _class3), (_applyDecoratedDescriptor(_class2.prototype, "isInitCard", [_dec3], Object.getOwnPropertyDescriptor(_class2.prototype, "isInitCard"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleWindowResize", [_dec4, _dec5], Object.getOwnPropertyDescriptor(_class2.prototype, "handleWindowResize"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "onLayoutChange", [_dec6], Object.getOwnPropertyDescriptor(_class2.prototype, "onLayoutChange"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "saveLayout", [_dec7], Object.getOwnPropertyDescriptor(_class2.prototype, "saveLayout"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "startSettingLayout", [_dec8], Object.getOwnPropertyDescriptor(_class2.prototype, "startSettingLayout"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "cancelSettingLayout", [_dec9], Object.getOwnPropertyDescriptor(_class2.prototype, "cancelSettingLayout"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "getCard", [_dec10], Object.getOwnPropertyDescriptor(_class2.prototype, "getCard"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "loadCards", [_dec11], Object.getOwnPropertyDescriptor(_class2.prototype, "loadCards"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleRemoveCard", [_dec12], Object.getOwnPropertyDescriptor(_class2.prototype, "handleRemoveCard"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleAddCard", [_dec13], Object.getOwnPropertyDescriptor(_class2.prototype, "handleAddCard"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "hideModal", [_dec14], Object.getOwnPropertyDescriptor(_class2.prototype, "hideModal"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "showModal", [_dec15], Object.getOwnPropertyDescriptor(_class2.prototype, "showModal"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "loadAssignableCards", [_dec16], Object.getOwnPropertyDescriptor(_class2.prototype, "loadAssignableCards"), _class2.prototype)), _class2)) || _class) || _class) || _class);
export { Workplace as default };